/**
 *
 * Copyright 2015 RSVP Technologies Inc. All rights reserved.
 * GeoConvert.java
 *
 */
package com.gfinal.map.geoconv;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gfinal.map.common.Constant;
import com.gfinal.map.util.HttpUtils;
import com.gfinal.map.util.Print;

/**
 * 坐标转换
 * 
 * @author Gao Yudong (gyd@nbicc.com)
 * @date 2015-3-2
 */
public class GeoConvert {
	private static final String TAG = GeoConvert.class.getName();

	/**
	 * 待转化坐标列表 格式：经度,纬度;经度,纬度… 限制：最多支持100个 格式举例： 114.21892734521,29.575429778924
	 * 114.21892734521,29.575429778924;114.21892734521,29.575429778924
	 */
	private List<Coord> coords = new ArrayList<Coord>();

	/**
	 * 源坐标类型 取值为如下：
	 * 1：GPS设备获取的角度坐标;
	 * 2：GPS获取的米制坐标、sogou地图所用坐标;
	 * 3：google地图、soso地图、aliyun地图、mapabc地图和amap地图所用坐标
	 * 4：3中列表地图坐标对应的米制坐标
	 * 5：百度地图采用的经纬度坐标
	 * 6：百度地图采用的米制坐标
	 * 7：mapbar地图坐标;
	 * 8：51地图坐标
	 */
	private int from = 1;
	
	/**
	 * 目的坐标类型
	 * 有两种可供选择：5、6
	 * 5：bd09ll(百度经纬度坐标)
	 * 6：bd09mc(百度米制经纬度坐标)
	 */
	private int to = 5;

	public void setCoords(List<Coord> coords) {
		this.coords = coords;
	}

	public void setFrom(int from) {
		this.from = from;
	}

	public void setTo(int to) {
		this.to = to;
	}
	
	@SuppressWarnings({"rawtypes", "unchecked"})
	private String createURI() {
		ArrayList params = new ArrayList();
		params.add(new BasicNameValuePair("ak", Constant.BAIDU_AK));
		params.add(new BasicNameValuePair("output", "json"));
		params.add(new BasicNameValuePair("from", String.valueOf(from)));
		params.add(new BasicNameValuePair("to", String.valueOf(to)));
		StringBuffer coordsSb = new StringBuffer();
		for(int i = 0; i < coords.size(); i++) {
			Coord l = coords.get(i);
			String coord = l.getX() + "," + l.getY();
			if(i != coords.size() - 1) {
				coord += ";";
			}
			coordsSb.append(coord);
		}
		params.add(new BasicNameValuePair("coords", coordsSb.toString()));
		return Constant.GEO_CONVERT_URL + "?"
				+ URLEncodedUtils.format(params, Constant.CHARSET);
	}
	
	public List<Coord> executes() {
		List<Coord> result = new ArrayList<Coord>();
		String response = HttpUtils.doGet(createURI());
		JSONObject obj = JSON.parseObject(response);
		if (obj.getIntValue("status") == 0) {
			result = JSON.parseArray(obj.getString("result"), Coord.class);
		}
		
		return result;
	}
	
	public static void main(String[] args) {
		GeoConvert convert = new GeoConvert();
		convert.setFrom(1);
		convert.setTo(5);
		List<Coord> coords = new ArrayList<Coord>();
		coords.add(new Coord(121.5608240000f, 29.8759640000f));
		convert.setCoords(coords);
		List<Coord> result = convert.executes();
		Print.pln(TAG, result);
	}
}
